package com.bbg.amyam.web.service.login;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import com.bbg.amyam.web.mvc.exception.NoSchoolFoundException;
import com.bbg.amyam.web.util.RequestPathParameter;
import com.bbg.amyam.web.util.RequestPathPaser;

public class AuthorizationDeniedService extends AccessDeniedHandlerImpl {

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		Principal principle = request.getUserPrincipal();
		if (principle == null) {
			RequestPathParameter param = null;
			try {
				param = RequestPathPaser.parse(request);
			} catch (NoSchoolFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (param != null) {
				this.setErrorPage("/" + param.getSchool().getShortName()
						+ "/login");
			}
		}
		super.handle(request, response, accessDeniedException);
	}

}
